package com.atguigu.gmall.service.impl;

import com.atguigu.gmall.entity.ProductImage;
import com.atguigu.gmall.entity.ProductSalePropertyKey;
import com.atguigu.gmall.entity.ProductSalePropertyValue;
import com.atguigu.gmall.entity.ProductSpu;
import com.atguigu.gmall.mapper.SpuMapper;
import com.atguigu.gmall.service.ImageService;
import com.atguigu.gmall.service.SalePropertyKeyService;
import com.atguigu.gmall.service.SalePropertyValueService;
import com.atguigu.gmall.service.SpuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional //加事务控制
public class SpuServiceImpl extends ServiceImpl<SpuMapper, ProductSpu> implements SpuService {

    @Autowired
    private SalePropertyKeyService salePropertyKeyService;
    @Autowired
    private SalePropertyValueService salePropertyValueService;
    @Autowired
    private ImageService imageService;
    @Override
    public IPage selectPageByCategory3Id(IPage<ProductSpu> productSpuPage, Long category3Id) {
        QueryWrapper<ProductSpu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category3_id", category3Id);
        queryWrapper.orderByDesc("id");
        return baseMapper.selectPage(productSpuPage, queryWrapper);
    }

    @Override
    public void saveInfo(ProductSpu productSpu) {

        /*添加基本的数据*/
        baseMapper.insert(productSpu);
        /*回显新增产品的id*/
        Long id = productSpu.getId();
        //获取销售属性集合
        List<ProductSalePropertyKey> salePropertyKeyList = productSpu.getSalePropertyKeyList();
        //迭代设置产品id
        for (ProductSalePropertyKey productSalePropertyKey : salePropertyKeyList) {
            productSalePropertyKey.setProductId(id);
            //获取销售属性的value值
            List<ProductSalePropertyValue> salePropertyValueList = productSalePropertyKey.getSalePropertyValueList(); //当前key属性值集合
            salePropertyValueList.stream().forEach(item -> {
                //迭代设置产品id
                item.setProductId(id);
                item.setSalePropertyKeyName(productSalePropertyKey.getSalePropertyKeyName());
            });
            //将value执行批量存储
            salePropertyValueService.saveBatch(salePropertyValueList);
        }
        //将key存储到product_sale_property_value 中
        salePropertyKeyService.saveBatch(salePropertyKeyList);//批量新增key

        List<ProductImage> productImageList = productSpu.getProductImageList();//图片集合
        for (ProductImage productImage : productImageList) {
            productImage.setProductId(id);
        }
        //存储到商品图片库中
        imageService.saveBatch(productImageList);
    }
}
